package com.lollipop.schedule.task;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Author: J.K
 * @Date: 2022-09-27 15:24
 * @Description:
 */
@Data
@Component
@Slf4j
@PropertySource("classpath:task-config.ini")
public class ScheduleTimerTask implements SchedulingConfigurer {

    @Value("${printTime.cron}")
    private String cron;
    /**
     * 单位毫秒
     */
    private Long timer = 10000L;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        // 动态使用cron表达式设置循环间隔
        taskRegistrar.addTriggerTask(() -> log.info("Current time： {} ======== timer", LocalDateTime.now()), triggerContext -> {
            // 使用不同的触发器，为设置循环时间的关键，区别于CronTrigger触发器，该触发器可随意设置循环间隔时间，单位为毫秒
            PeriodicTrigger periodicTrigger = new PeriodicTrigger(timer);
            Date nextExecutionTime = periodicTrigger.nextExecutionTime(triggerContext);
            return nextExecutionTime;
        });
    }
}

